<template>
  <div class="image-container">
    <el-card class="box-card">
      <div slot="header">
       <my-breadcrumb>素材管理</my-breadcrumb>
      </div>
      <div style="padding-bottom: 20px;">
        <el-radio-group v-model="isCollected" size="mini" @change="hToggle">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
         <el-button
         @click="dialogVisible=true"
         type="success" size="mini" style="float:right">上传图片素材</el-button>
      </div>
      <!-- 素材列表 -->
      <el-row :gutter="10">
        <el-col  class="img_item" :xs="12" :sm="6" :md="6" :lg="4" v-for="image in images" :key="image.id">
          <el-image
            style="height: 180px;width: 180px"
            :src="image.url"
            fit="cover"
          ></el-image>
          <div class="option" v-show="!isCollected">
            <span class="el-icon-star-off" :class="{'red': image.is_collected}" @click="hSwitchCollect(image)"></span>
            <span class="el-icon-delete" @click="hDelete(image.id)"></span>
          </div>
        </el-col>
      </el-row>
      <!-- /素材列表 -->
      <el-pagination
      background
      :page-size="10"
      layout="prev, pager, next"
      :total="total_count"
      style="margin-top:35px"
      @current-change="hPag"
      >
      </el-pagination>
    </el-card>
     <el-dialog
      title="素材上传"
      append-to-body
      :visible.sync="dialogVisible">
      <el-upload
        class="avatar-uploader"
        action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
        :headers="headers"
        name="image"
        :show-file-list="false"
        :before-upload="hBeforeUpload"
        :on-success="hUploadSuccess"
        >
        <!-- img用来显示上传成功之后的图像 -->
        <el-image v-if="imageUrl" :src="imageUrl" @load="hpreviewImageload" class="avatar" />
        <!-- 显示引导用户上传的 那个 + 号 -->
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>

      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ImageIndex',
  data () {
    return {
      dialogVisible: false, // 是否显示弹出对话框
      curPage: 1, // 当前查询第几页
      total_count: 100, // 查询的总数量
      images: [], // 素材列表
      isCollected: false, // 是否是 收藏的图片， true表示是收藏，false表示是全部
      headers: {
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      },
      imageUrl: '' // 图片的预览地址
    }
  },
  created () {
    this.loadImages()
  },
  methods: {
    // 删除功能处理函数
    async doDelete (id) {
      try {
        const res = await this.$http({
          url: '/mp/v1_0/user/images/' + id,
          method: 'DELETE'
        })
        this.$message.success('操作成功')
        console.log(res)
        // 发请求更新
        this.loadImages()
      } catch (err) {
        // console.log(err)
        this.$message.error('操作失败')
      }
    },
    // 用户删除图像
    hDelete (id) {
      this.$confirm('确定删除吗?').then(() => {
        this.doDelete(id)
      }).catch(() => {
      })
    },
    // 收藏/取消收藏图片处理函数
    async hSwitchCollect (image) {
      // image是当前用户选中收藏与否 时， 所操作那张图
      const imageId = image.id
      console.log(image)
      try {
        // 调用接口，传递参数
        const res = await this.$http({
          url: '/mp/v1_0/user/images/' + imageId,
          method: 'PUT',
          data: {
            // false-取消收藏，true-添加收藏
            collect: !image.is_collected
          }
        })
        console.log(res)
        this.$message.success('操作成功')
        image.is_collected = !image.is_collected
      } catch (err) {
        console.log(err)
        this.$message.error('操作失败')
      }
    },
    // 上传图片等待两秒自动关闭函数
    hpreviewImageload () {
      setTimeout(() => {
        this.dialogVisible = false
        this.imageUrl = ''
      }, 2000)
    },
    hUploadSuccess (res, file) {
      // 1. 预览效果
      this.imageUrl = res.data.url
      // 2. 重新请求一次
      this.loadImages()
    },
    hBeforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      // file.size 单位是字节
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 筛选条件切换函数
    hToggle () {
      //  更新页码 为1
      this.curPage = 1
      // 重新发请求
      this.loadImages()
    },
    // 页码改变后事件
    hPag (page) {
      this.curPage = page // 点击页码后更新页码
      this.loadImages() // 重发请求
    },
    async loadImages () {
      // 发请求，获取数据，保存到images中
      const res = await this.$http({
        url: '/mp/v1_0/user/images',
        method: 'GET',
        params: {
          per_page: 10, // 每页固定10条
          collect: this.isCollected, // 是否是收藏的图片
          page: this.curPage
        }
      })
      this.total_count = res.data.data.total_count // 更新总条数
      this.images = res.data.data.results // 图片数据赋值images
    }
  }
}
</script>

<style lang="less" scoped>
  .img_item {
    position: relative;
    box-sizing: border-box;
  }
  .option {
    position: absolute;
    left: 5px;
    width:180px;
    bottom: 5px;
    height: 30px;
    line-height: 30px;
    background: rgba(0, 0, 0, 0.3);
    text-align: center;
    color: #fff;
    span {
      margin: 0 30px;
      cursor: pointer;
    }
  }
.avatar-uploader {
    text-align: center;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.red {
   color: red;
}
</style>
